const koaRouter = require('koa-router');
const koaBetterBody = require('koa-better-body');
const koaConvert = require('koa-convert');
const fs = require('fs');
const pathLib = require('path');

let router = new koaRouter({
    prefix: '/task'
});

let task = JSON.parse(fs.readFileSync(pathLib.resolve(__dirname, '../../data/task.json')));

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        todoTitle: task.todoTitle,
        task: task.datas
    });
});

router.get('/add', async (ctx, next) => {
    await ctx.render('add', {
        todoTitle: task.todoTitle
    });
});

router.post('/add', koaConvert(koaBetterBody({
    buffer: false,
    multipart: false
})), async (ctx, next) => {
    let {
        title
    } = ctx.request.fields;

    if (!title) {
        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务添加失败',
            path: '/task/add',
            tips: '返回新增页'
        });

        return false;
    } else {
        task.datas.push({
            ID: ++task._id,
            title,
            done: false
        });

        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务添加成功',
            path: '/task',
            tips: '返回首页'
        });

        fs.writeFileSync(pathLib.resolve(__dirname, '../../data/task.json'), JSON.stringify(task));
    }
});

router.get('/update/:id', async (ctx, next) => {
    let {
        id
    } = ctx.params;

    if (!id) {
        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务更新失败',
            path: '/task',
            tips: '返回首页'
        });
    } else {
        task.datas.find(item => {
            if (item.ID == id) {
                item.done = !item.done;
            }
        });

        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务更新成功',
            path: '/task',
            tips: '返回首页'
        });

        fs.writeFileSync(pathLib.resolve(__dirname, '../../data/task.json'), JSON.stringify(task));
    }
});

router.get('/delete/:id', async (ctx, next) => {
    let {
        id
    } = ctx.params;

    if (!id) {
        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务删除失败',
            path: '/task',
            tips: '返回首页'
        });
    } else {
        task.datas = task.datas.filter(item => item.ID != id);

        await ctx.render('message', {
            todoTitle: task.todoTitle,
            msg: '任务删除成功',
            path: '/task',
            tips: '返回首页'
        });

        fs.writeFileSync(pathLib.resolve(__dirname, '../../data/task.json'), JSON.stringify(task));
    }
});

module.exports = router.routes();